﻿using Microsoft.AspNetCore.Http;

namespace Devonline.AspNetCore;

/// <summary>
/// 全局请求相关中间件
/// </summary>
public class GlobalRequestMiddleware(RequestDelegate next)
{
    private readonly RequestDelegate _next = next;

    /// <summary>
    /// 中间件执行方法
    /// </summary>
    /// <param name="context"></param>
    /// <param name="httpSetting"></param>
    /// <returns></returns>
    public async Task InvokeAsync(HttpContext context, HttpSetting httpSetting)
    {
        if (httpSetting.AutoFilter)
        {
            //设置全局自动分页查询
            SetAutoFilter(context.Request, httpSetting);
        }

        // Call the next delegate/middleware in the pipeline.
        await _next(context);
    }

    /// <summary>
    /// 设置 PagedRequest 模式自动查询过滤设定
    /// </summary>
    private void SetAutoFilter(HttpRequest request, HttpSetting httpSetting)
    {
        var filter = request.GetRequestOption<string>(QUERY_REQUEST_FILTER);
        var autoFilter = !string.IsNullOrWhiteSpace(filter);
        if (!autoFilter && httpSetting.AutoFilter)
        {
            autoFilter = true;
            request.SetRequestHeader(QUERY_REQUEST_FILTER, DEFAULT_VALUE_TRUE);
        }

        if (autoFilter)
        {
            var defaultOperatorType = nameof(HttpSetting.DefaultOperatorType).ToCamelCase();
            var operatorType = request.GetRequestOption<string>(defaultOperatorType) ?? httpSetting.DefaultOperatorType.ToString();
            request.SetRequestHeader(defaultOperatorType, operatorType);
        }
    }
}